package ch5;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 演示Condition接口的使用方法
 */

public class ConditionUsage {
    private final Lock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();
    private static boolean flag = false;

    public void aGuardedMethod() throws InterruptedException {
        lock.lock();
        try {
            while (flag/*保护条件不成立*/) {
                condition.await();
            }
            doAction();
        } finally {
            lock.unlock();
        }
    }

    private void doAction() {
        // do something
    }

    public void anNotificationMehtod() {
        lock.lock();
        try {
            // 更新共享变量
            changeState();
            condition.signal();
        } finally {
            lock.unlock();
        }
    }

    private void changeState() {
        // do something
    }
}

